#coding=utf-8
#LightCam 组播监控程序
#init by hfh 20150212

import multiprocessing,subprocess,threading
import socket,os,time,re,traceback,sys
import lc_libs
import telnetlib,base64


def func(this):

	agent_hostname=this['agent_hostname']
	devicename=this['devicename']
	deviceip=this['deviceip']
	port=this['port']
	keyword=this['keyword']
	interval=this['interval']
	severity=this['severity']
	schedule=this['schedule']
	holiday=this['holiday']
	
	print devicename
	
	thisvalue=0
	lastvalue=0
	initflag=0
	USER="monitor"
	PASSWD="IWNmZkV4MjAwN1w="

	try:
		Node=agent_hostname
		AlertGroup="MultiCast"
		AlertKey=devicename+"_"+port
		Summary=""
	
		#执行进程监控
		USER="monitor"
		PASSWD="IWNmZkV4MjAwN1w="
		tn = telnetlib.Telnet(deviceip,port=23,timeout=10)
		tn.read_until("sername:")
		tn.write(USER+"\n")
		tn.read_until("assword:")
		tn.write(base64.decodestring(PASSWD)+"\n")
		tn.read_until("#")

		comd="sh int "+str(port)
		tn.write(comd+" \n")
		time.sleep(1)
		res=""
		i=0
		out=""
		resline=""
		while True:
			res=tn.read_very_eager()
			for line in res.split('\n'):
				if "More" not in line:
					if keyword in line:
						resline=line
					out=out+line+"\n"
			if out[-2]=="#":
				tn.write("exit\n")
				break
			elif "More" in res:
				tn.write(" ")
				time.sleep(0.01)
			else:
				time.sleep(1)
				i=i+1
				if i > 10:
					break
		tn.close()
		if keyword=='Received':
			thisvalue=int(re.findall(r"\((.*) multicast",resline,re.S)[0].strip(' '))
		elif keyword in ('L3 in','L3 out'):
			thisvalue=int(re.findall(r"mcast:(.*)pkt",resline,re.S)[0].strip(' '))

		#初始化标志文件
		try:
			alertfilename=lchome+"/alert/lc_multicast_"+devicename+"_"+port.replace("/","_")
			rf=open(alertfilename)
			lastvalue=float(rf.read().split(',')[7])
			rf.close()
		except:
			pass
		#处理程序
		value=thisvalue-lastvalue
		value=float(value)/float(interval)
		value=str("%.2f" % value)
		lastvalue=thisvalue
		line=devicename+" "+deviceip+" "+port+" "+str(value)
		line="MultiCast,"+devicename+"_"+port+","+deviceip+","+str(value)+","+time.strftime('%Y%m%d%H%M%S',time.localtime())+",ywn_monitor1,0,Error,"
		line="MultiCast,"+devicename+"_"+port+","+deviceip+",0,"+time.strftime('%Y%m%d%H%M%S',time.localtime())+",ywn_monitor1,"+str(value)+","+str(thisvalue)+","
		outputfile=open(alertfilename,"w")
		outputfile.write(line+"\n")
		outputfile.close()
		#数据入库
		#hdb.insert_historydb(Node,procname,Summary)
		#datas=[
		#	{"Node":Node,"Name":procname,"Value":Summary.decode('gbk'),"Time":int(time.time())}
		#	]
		#db.insertDatas(history_table,datas)
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%b %d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+" "+devicename+"\n")
		logfile.flush()
		time.sleep(1)


if __name__ == "__main__":

	cmd='echo $LIGHTCAM_HOME'
	popen=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	while True:
		if popen.poll()==None:
			time.sleep(0.1)
			continue
		else:
			break
	lchome=popen.stdout.read().strip('\r\n')
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	agent_hostname=lc_libs.lc_gethostname()
	
	try:
		#初始化数据库
		
		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

		db.connect()
		Conn=db.getConn()
		if Conn==None:
			print "Can not Connect to the MondbDB"
			exit(0)
		
		events_dbname='lc_events'
		events_tablename='lc_events'
		
		history_dbname='lc_history'
		history_tablename="lc_process"
		
		events_db=db.useDatabase(events_dbname)
		events_table=db.UseCollection(events_db,events_tablename)
		
		history_db=db.useDatabase(history_dbname)
		history_table=db.UseCollection(history_db,history_tablename)

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%b %d %H:%M:%S',time.localtime())
		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
		logfile.flush()
		exit(0)

	#主程序
	MonitorList = []
	
	for lines in open(confname):
		if lines[0] == '#' or lines.split("\t")[0] not in (agent_hostname,'default'):
			continue

		line=lines.strip('\r\n').split('\t')
		dconf={}
		
		dconf['agent_hostname']=line[0]
		dconf['devicename']=line[1]
		dconf['deviceip']=line[2]
		dconf['port']=line[3]
		dconf['keyword']=line[4]
		dconf['interval']=line[5]
		dconf['severity']=line[6]
		dconf['schedule']=line[7]
		dconf['holiday']=line[8]
	
		MonitorList.append(dconf)

	timeflag=int(time.time())
	
	while True:
		time.sleep(1)
		timeflag+=1
		realtime=int(time.time())
		#print realtime
		
		logdate=time.strftime('%b %d %H:%M:%S',time.localtime())
		
		threads = []
		
		for i in MonitorList:
			holiday_state = lc_libs.lc_isholiday()
			if int(i['holiday']) == 1 and holiday_state == True:
				continue
				
			time_state = lc_libs.lc_schedule(i['schedule'])
			if time_state == False:
				continue
			
			flag=realtime%int(i['interval'])
			if flag<=realtime-timeflag:
				#print i
				t = threading.Thread(target=func,args=(i,))
				threads.append(t)

		timeflag=int(time.time())
		for t in threads:
			t.start()
			while True:
				#print len(threading.enumerate())
				time.sleep(0.1)
				if(len(threading.enumerate()) < 10):
					break
